%
clear all
close all %comment this out if you want to plot additional data on the tag figures. 
% So to add unfiltered data on top of filtered: comment out "close all" and
% change dotted line properties below.



%%
%directory selection loop

%initialize variables for looping
button='select another';
files=struct('path','','name','','tag',0,'processed',0); % initialize files structure
f=1; %the files count index, used for keeping track of the next position in the files structured array to put a new entry
tags=[];%initialize the tags found array
t=1;%tags index that keeps track of the next tag value to update

%begin the directory processing loop, end loop when user selects done on
%a two button dialog
while strcmp(button,'select another');
    directoryName=uigetdir('D:\Lotek\Capture History Data\Batch Test PRSC_3','Select the next directory to process'); %user dialog for directory
    contents=dir(directoryName); %list contents of directory in a structure
    L=length(contents);
    %begin contents sorting loop
    for i=1:L
        if ~contents(i).isdir %if the component is a directory, skip
            workingName=contents(i).name;
            LL=length(workingName);
            type=workingName(LL-2:LL);
            if strcmp(type,'csv') %only preceed if the type of the file is csv
               breaks=regexp(workingName(1:LL-4),'_');%look for the underscore that denotes the tag code
               if ~isempty(breaks)%if an underscore if found proceed, otherwise ignore
                   lastbreak=max(breaks);
                   tagString=workingName(lastbreak+1:LL-4);
                   tag=str2double(tagString);
                   %update the files to process structure;
                   files(f).path=strcat(directoryName,'\');%add an backslash to the directory name 
                   %so that it can be concatonated with the file name for
                   %easy loading in the future.
                   files(f).name=workingName;
                   files(f).tag=tag;
                   files(f).processed=0;
                   %update the tags to be processed list array
                   tags(t)=tag;
                   %index the files and tags array index variables forward
                   f=f+1;
                   t=t+1;
               end %end the " a break must be found" if
            end% end the "must be a .csv file" if
        end% end the "must not be a directory if
    end%end the directory contents loop

    %determine if the user wants to search another directory
   button=questdlg('Do you want to select another directory to process','Select another?','select another','Done','select another');
end%end the directory while loop.

%%
%now, process the files that are selected

%initialize the captures array
captures=struct('tag',0,'caps',[]);
c=1; %initialize the captures next new value index
maxStation=0; %this variable keeps track of the maximum station code value 
%seen in this processing run, this number will be used to create a color
%map of station for plotting

%if the files or tags arrays are empty, don't proceed
if ~isempty(tags) && ~isempty(files)
    tagVals=unique(tags); %find the individual unique tag values
    for t=1:length(tagVals); %loop through the individual tag values, and process each file for this tag
        inds=find(tags==tagVals(t));%find all the files with for this tag (indifferent directories)
        capHist=[];
        for i=1:length(inds)%loop through each occurence of this tag
            capHist=[capHist;captureHistoryFun(files(inds(i)).path,files(inds(i)).name)]; %update the capture history array for this file
            files(inds(i)).processed=1; %update the files structured array to indicate that this occurence has been processed
        end %end looping through the individual files for each tag, now capHist contains all the histories for this tag across all directories
        %sort capHist, and then add it and its tag value to the structured
        %array of finished capture histories.
        capHist=sortrows(capHist,1); %sort the captures in time, so they are no longer stuctured by file (e.g., station)
        %update the captures structure
        captures(c).tag=tagVals(t);
        captures(c).caps=capHist;
        stationMax=max(capHist(:,5)); %get the maximum of the station value code;
        maxStation=max([maxStation,stationMax]); %make sure that maxStation contains the highest station code yet seen
        %index the captures structure index
        c=c+1;
    end %end the loop that performs the captureHistory calculation for each individual tag value
    
end%end the "continue if arrays are not empty" if

%%
%wite output files
[fname,fpath]=uiputfile('*.csv','select basepath for capture history files'); %get the base file name and directory for the output files

%create a color map for the stations
% cmap=flag(maxStation);
cmap=...
    [ 0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5;...
      0, 0, 0;...
     .5,.5,.5];
 %loop through the entries for each tag in the captures structured array,
%use the .tag field to automatically incriment the file name for each tag,
%write the .caps field to file.
for i=1:length(captures)
    dlmwrite(strcat(fpath,fname(1:length(fname)-4),'_captures_',num2str(captures(i).tag),'.csv'),captures(i).caps,'delimiter',',','precision',10);
    h=figure(captures(i).tag);
    patchCaptures(h,captures,i,cmap,'indiv');
end
%plot the common tags figure
h=figure;

%create a randomized color map
mtag=length(tagVals);
cmap=jet(mtag);
newMap=zeros(size(cmap));
%%Randomize the color map
% for i=1:mtag
%     [L,W]=size(cmap);
%     ind=round(rand*L);
%     if ind<1
%         ind=1;
%     elseif ind>L
%         ind=L
%     end
%     newMap(i,:)=cmap(ind,:);
%     cmap(ind,:)=[];
% end
% cmap=newMap; 
figure(h)
for i=1:length(captures)
    if captures(i).tag >=10 & captures(i).tag <=59  % Make sure tag range is correct 10-59!     
        patchCaptures(h,captures,i,cmap,'common');
    end
end
%this section of code changes the xtick labels from julian days to
%text, with a minimum width of 1 day.  Ticks are at midnight.
xl=xlim;
lower=floor(xl(1));
upper=ceil(xl(2));
if upper-lower<1
    upper=upper+1;
end
if upper-lower+1>10
    xticks=lower:round((upper-lower)/10):upper;   
else
    xticks=lower:1:upper;   
end
xlabels=cell(size(xticks));
for j=1:length(xticks);
    xlabels{j}=datestr(xticks(j)+datenum(2011, 1, 1, 0, 0, 0)-1,'mm-dd');
end
set(gca,'xtick',xticks,'xticklabel',xlabels);
xlim([lower,upper]);
xlabel('Date')
title('Capture History All Tags')
%colormap(cmap);
%colorbar('EastOutside');
axis tight
        
            
        
    
    